package odooapi

import (
	"bytes"
	"encoding/json"
	"fmt"
	"net/http"

	"github.com/imdario/mergo"
)

type PageInfo struct {
	Offset int
	Limit  int
	Sort   string
}

// Call calls remote Odoo method
func (client *Client) SearchReadPages(model string, domain []interface{}, fields []string, pageInfo *PageInfo) (interface{}, error) {
	url := fmt.Sprintf("%s/web/dataset/search_read", client.BaseURL)

	context := map[string]interface{}{}
	mergo.Merge(&context, client.Auth.Result.UserContext)

	requestPayload := map[string]interface{}{
		"id":      1,
		"jsonrpc": "2.0",
		"method":  "call",
		"params": map[string]interface{}{
			"context": context,
			"model":   model,
			"domain":  domain,
			"fields":  fields,
			"offset":  pageInfo.Offset,
			"limit":   pageInfo.Limit,
			"sort":    pageInfo.Sort,
		},
	}
	payloadBuf, err := json.Marshal(requestPayload)
	if err != nil {
		return nil, err
	}

	request, err := http.NewRequest("POST", url, bytes.NewReader(payloadBuf))
	if err != nil {
		return nil, err
	}
	request.Header.Add("Content-Type", "application/json")
	request.Header.Add("Accept", "application/json")

	httpResponse, err := client.HttpClient.Do(request)
	if err != nil {
		return nil, err
	}
	defer httpResponse.Body.Close()

	response := &RPCResponse{}
	err = json.NewDecoder(httpResponse.Body).Decode(response)
	if err != nil {
		return nil, err
	}

	if response.Error != nil {
		return nil, fmt.Errorf("RPC Error: %s", response.Error.Data.Message)
	}

	if response.Result == nil {
		return nil, fmt.Errorf("RPC returned no result")
	}

	return response.Result, nil
}
